package com.mentalhealth.diary.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

/**
 * Spring Security配置类
 * 配置密码编码器和安全过滤器链
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    /**
     * 配置BCrypt密码编码器
     * @return 密码编码器实例
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 配置安全过滤器链
     * @param http HTTP安全配置
     * @return 安全过滤器链
     * @throws Exception 配置异常
     */
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            // 暂时禁用CSRF保护，适用于API接口
            .csrf(csrf -> csrf.disable())
            // 允许跨域请求
            .cors(cors -> cors.disable())
            // 配置请求授权规则
            .authorizeHttpRequests(authorize -> authorize
                // 允许所有请求通过（实际项目中应该根据需要配置权限）
                .anyRequest().permitAll()
            )
            // 关闭默认的表单登录
            .formLogin(form -> form.disable())
            // 关闭默认的HTTP基本认证
            .httpBasic(basic -> basic.disable());

        return http.build();
    }
}